/** this one is buggy but does work for small input.
 */

#include <stdio.h>
#include <stdlib.h>

int getfine(char* s);

/* getline:  read a line into s, return length  */
int getfine(char* s)
   {
       int c, i;
       for (i=0; ((c=getchar())!=EOF) && c!='\n'; i++)
       {
           *s = c;
           s++;
       }
       if (c == '\n')
       {
           *s = 0;
           ++i;
       }
       //printf("%d : len \n",i);
       return i-1;

   }

int LINES=-1; // everything by default.
int MAXLINES=100000;

int main(int argc, char *argv[])
{

  char *lineptr[MAXLINES];
  //  while (argv!=0 && *argv!=0)
  //  {argv--;}
  // -m
  argv++;
  if (argc > 1)
    {
      while (argv!=0 && *argv!=0)
        {
          if ((*argv)[0]=='-' && (*argv)[1]=='n')
            {
              argv++;
              LINES=atoi(*argv);
              break;
            }
        }
    }
  int ret=0;
  int i =0;
  for (; ; i++)
    {
      char *line = malloc(sizeof(char)*1000);
      ret=getfine(line);
      if (ret==0) break; //eof
      lineptr[i]=line;
    }
  for (int j=0;j<i ; j++)
    {
        if ( j>=i-LINES || (LINES<0))
        {
          printf("%s\n",lineptr[j]);
          free(lineptr[j]);
          continue;
        }
        if ( (j<=i-LINES) )
        {
            free(lineptr[j]);
        }
    }
}
